package com.self.finance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.self.common.exception.BusinessException;
import com.self.common.model.Config;
import com.self.common.service.ConfigService;
import com.self.finance.constant.FinanceConstant;
import com.self.finance.model.AccountDetail;
import com.self.finance.model.Coin;
import com.self.finance.service.AccountDetailService;
import com.self.finance.service.CoinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.self.finance.model.Account;
import com.self.finance.mapper.AccountMapper;
import com.self.finance.service.AccountService;
import org.springframework.util.Assert;

@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService{

    @Autowired
    private AccountDetailService accountDetailService;

    @Autowired
    private CoinService coinService;

    @Autowired
    private ConfigService configService;


    @Override
    public boolean transferAccountAmount(long adminId, Long userId, Long coinId, Long orderNo, BigDecimal num, BigDecimal fee,
                                         String businessType,Byte direction,String remark) {
        Account account = getCoinAndAccount(coinId,userId);
        Assert.notNull(account,"当前币种余额不存在");
        AccountDetail accountDetail = new AccountDetail();
        accountDetail.setCoinId(coinId);
        accountDetail.setAmount(num);
        accountDetail.setFee(fee);
        accountDetail.setRefAccountId(adminId);
        accountDetail.setAccountId(adminId);
        accountDetail.setOrderId(orderNo);
        accountDetail.setBusinessType(businessType);
        accountDetail.setDirection(direction);
        accountDetail.setRemark(remark);
        boolean save = accountDetailService.save(accountDetail);
        if (save){
            account.setBalanceAmount(account.getBalanceAmount().add(num));
            return updateById(account);
        }
        return false;
    }

    @Override
    public Account findByUserAndCoin(Long userId, String coinName) {
        Coin coin =  coinService.getCoinByCoinName(coinName);
        Assert.notNull(coin,"货币不存在");
        Account account = getCoinAndAccount(coin.getId(), userId);
        Assert.notNull(account,"该资产不存在");
        Config sellRateConfig = configService.findByCode(FinanceConstant.CONFIG_CODE_USDT2CNY);
        account.setSellRate(new BigDecimal(sellRateConfig.getValue())); // 出售的费率

        Config setBuyRateConfig = configService.findByCode(FinanceConstant.CONFIG_CODE_CNY2USDT);
        account.setBuyRate(new BigDecimal(setBuyRateConfig.getValue())); // 买进来的费率
        return account;
    }

    private Account getCoinAndAccount(Long coinId,Long userId){
        return getOne(new LambdaQueryWrapper<Account>()
                .eq(Account::getCoinId,coinId)
                .eq(Account::getUserId,userId)
                .eq(Account::getStatus,1));
    }

    @Override
    public boolean decreaseAccountAmount(long adminId, Long userId, Long coinId, Long orderNo, BigDecimal num, BigDecimal fee, String businessType, byte direction, String remark) {
        Account account = getCoinAndAccount(coinId,userId);
        Assert.notNull(account,"当前币种余额不存在");
        AccountDetail accountDetail = new AccountDetail();
        accountDetail.setCoinId(coinId);
        accountDetail.setAmount(num);
        accountDetail.setFee(fee);
        accountDetail.setRefAccountId(adminId);
        accountDetail.setAccountId(adminId);
        accountDetail.setOrderId(orderNo);
        accountDetail.setBusinessType(businessType);
        accountDetail.setDirection(direction);
        accountDetail.setRemark(remark);
        boolean save = accountDetailService.save(accountDetail);
        if (save){
            BigDecimal balanceAmount = account.getBalanceAmount();
            BigDecimal subtract = balanceAmount.subtract(num);
            if (BigDecimal.ZERO.compareTo(subtract) < 0){
                account.setBalanceAmount(subtract);
                return updateById(account);
            }else{
                throw new BusinessException("余额不足");
            }
        }
        return false;
    }

    @Override
    public void lockUserAmount(Long userId, Long coinId, BigDecimal mum, String type, Long orderId, BigDecimal fee) {
        Account account = getOne(new LambdaQueryWrapper<Account>().eq(Account::getUserId, userId)
                .eq(Account::getCoinId, coinId));
        Assert.notNull(account,"您输入的资产类型不存在");
        BigDecimal balanceAmount = account.getBalanceAmount();
        Assert.isTrue(balanceAmount != null && balanceAmount.compareTo(mum) < 0,"账号的资金不足");
        account.setBalanceAmount(balanceAmount.subtract(mum));
        account.setFreezeAmount(account.getFreezeAmount().add(mum));
        boolean updateById = updateById(account);
        if (updateById) {  // 增加流水记录
            AccountDetail accountDetail = new AccountDetail(
                    null,
                    userId,
                    coinId,
                    account.getId(),
                    account.getId(), // 如果该订单时邀请奖励,有我们的ref的account ,否则,值和account 是一样的
                    orderId,
                    (byte) 2,
                    type,
                    mum,
                    fee,
                    "用户提现",
                    null,
                    null,
                    null
            );
            accountDetailService.save(accountDetail);
        }
    }
}
